package com.sysd.mail.smtp;

import com.sysd.mail.config.ServerConfig;
import io.netty.channel.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * project: mail
 *
 * @author bsh
 * @description SmtpServerHandler
 * @dataTime 2022/12/28 7:59
 * @company 丽水信阳软件科技有限公司
 */
public class SmtpServerHandler extends SimpleChannelInboundHandler<String> {

    private final SmtpCommandHandler smtpCommandHandler = new SmtpCommandHandler();
    private final Map<Channel, SmtpSession> sessionMap = new ConcurrentHashMap<>();

    /**
     * <strong>Please keep in mind that this method will be renamed to
     * {@code messageReceived(ChannelHandlerContext, I)} in 5.0.</strong>
     * <p>
     * Is called for each message of type {@link String}.
     *
     * @param ctx the {@link ChannelHandlerContext} which this {@link SimpleChannelInboundHandler}
     *            belongs to
     * @param msg the message to handle
     * @throws Exception is thrown if an error occurred
     */
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        System.out.println("收到客户端的消息");
        System.out.println(msg);
        Channel channel = ctx.channel();
        SmtpSession smtpSession = smtpCommandHandler.handleCommand(sessionMap.get(channel), msg);
        sessionMap.put(channel, smtpSession);
    }

    /**
     * Do nothing by default, sub-classes may override this method.
     *
     * @param ctx the {@link ChannelHandlerContext} which this {@link SimpleChannelInboundHandler}
     *            belongs to
     */
    @Override
    public void handlerAdded(ChannelHandlerContext ctx) {
        Channel channel = ctx.channel();
        SmtpSession smtpSession = new SmtpSession(channel);
        sessionMap.put(channel, smtpSession);
        smtpSession.write("220 " + ServerConfig.DOMAIN + " ESMTP\r\n");
    }

    /**
     * Do nothing by default, sub-classes may override this method.
     *
     * @param ctx the {@link ChannelHandlerContext} which this {@link SimpleChannelInboundHandler}
     *            belongs to
     */
    @Override
    public void handlerRemoved(ChannelHandlerContext ctx) {

    }

    /**
     * Calls {@link ChannelHandlerContext#fireExceptionCaught(Throwable)} to forward
     * to the next {@link ChannelHandler} in the {@link ChannelPipeline}.
     * <p>
     * Sub-classes may override this method to change behavior.
     *
     * @param ctx   the {@link ChannelHandlerContext} which this {@link SimpleChannelInboundHandler}
     *              belongs to
     * @param cause exception case
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {

    }
}
